package com.quectel.util.servlet.filter;

import com.quectel.util.kit.TraceIdKit;
import javax.servlet.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.io.IOException;

/**
 * http拦截器生成追踪标识
 *
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022-12-01 13:51:00
 */
@Slf4j
public class HttpTraceIdFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        String traceId = TraceIdKit.getTraceId();
        MDC.put(TraceIdKit.TRACE_ID_KEY, traceId);
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("HttpTraceIdFilter catch exception", e);
            throw e;
        } finally {
            TraceIdKit.remove();
            MDC.remove(TraceIdKit.TRACE_ID_KEY);
        }

    }
}
